package com.cheneyjoo.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Optional;

public class ClientThread implements Runnable {
    private Socket socket = null;
    private BufferedReader in = null;
    public boolean isOnline = true;

    public ClientThread(Socket socket) throws IOException {
        this.socket = socket;
        in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }

    @Override
    public void run() {
        try{
            while (isOnline) {
                String readLine = in.readLine();
                if ("*server close*".equals(readLine)){
                    System.out.println("接收到服务器关闭信息");
                    break;
                }
                System.out.println(readLine);
            }
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(Optional.ofNullable(in).isPresent()){
                try {
                    in.close();
                    System.out.println("输入流关闭");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(Optional.ofNullable(socket).isPresent()){
                try {
                    socket.close();
                    System.out.println("socket关闭");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
